<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div id="message"></div>
    <script src="/sso/js/axios.min.js"></script>
    <script>
      axios.interceptors.response.use(
        function(response) {
          if (response.status === 200) {
            return response.data;
          } else {
            return Promise.reject(error);
          }
        },
        function(error) {
          return Promise.reject(error);
        }
      );

      const obj = {
        messageNode: document.getElementById("message"),
        origin: location.origin, // 当前域名
        apiHost: location.origin, // 接口请求域
        currentUrl: new URL(location.href),
        ssoUri: "http://passport.wz-inc.com/sso.html",
        ssoLogoutUri: 'http://passport.wz-inc.com/logout',
        api: {
          getToken: "/api/qxwz/login",
        },
      };

      /**
       * 设置错误信息内容
       * @param {string} val 内容
       * @return {void}
       */
      function setMessage(val) {
        obj.messageNode.innerText = val ? val : "";
      }

      /**
       * 初始化页面
       * @param {void}
       * @return {void}
       */
      function init() {
        const bucAuthToken = obj.currentUrl.searchParams.get("buc-auth-token");
        const isLogout = obj.currentUrl.searchParams.get("isLogout");

        if (bucAuthToken) {
          // 如果url有buc-auth-token参数，则说明sso已登录
          axios
            .get(obj.apiHost + obj.api.getToken, {
              params: { code: bucAuthToken },
            })
            .then((res) => {
              if (res && res.errcode === 0) {
                localStorage.setItem("token", res.access_token);
                location.replace(obj.origin);
              } else {
                setMessage("登录失败");
              }
            })
            .catch((err) => {
              setMessage("请求异常");
              console.log(err);
            });
        } else {
          // 反之需要跳转到sso进行登录
          const url = `${isLogout ? obj.ssoLogoutUri : obj.ssoUri}?return_url=${encodeURIComponent(
            obj.currentUrl.origin + obj.currentUrl.pathname
          )}`;
          location.replace(url);
        }
      }

      init();
    </script>
  </body>
</html>
